package com.silence.gankio.fragment

import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.silence.gankio.R
import com.silence.gankio.activity.IjkPlayerActivity
import com.silence.gankio.adapter.IsoyuVideoAdapter
import com.silence.gankio.bean.IsoyuBean
import com.silence.gankio.mvvm.viewModel.IsoyuVideoViewModel
import com.xuexiang.xui.utils.SnackbarUtils
import kotlinx.android.synthetic.main.recycle_fragment.*

class IsoyuVideoFragment : IsoyuFragment<IsoyuVideoViewModel>(), SwipeRefreshLayout.OnRefreshListener {

    override fun getModelClass() = IsoyuVideoViewModel::class.java

    override fun getFragmentContentView() = R.layout.recycle_fragment
    private val mAdapter by lazy { IsoyuVideoAdapter(null) }

    companion object {
        fun newInstance() = IsoyuVideoFragment()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        initListener()
        refresh_layout.post {
            refresh_layout.isRefreshing = true
            loadData(true)
        }
    }

    private fun initListener() {
        mBaseModel?.getVideoData()?.observe(this,
            Observer<IsoyuBean.DataBean> {
                mAdapter.loadMoreComplete()
                if (it == null) {
                    mAdapter.loadMoreFail()
                } else {
                    mAdapter.setNewData(it.videoList)
                    mAdapter.disableLoadMoreIfNotFullPage(recycler)
                }
                refresh_layout.isRefreshing = false
                mAdapter.setEnableLoadMore(true)
            })

        refresh_layout.setOnRefreshListener(this)

        mAdapter.onItemClickListener =
            BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
                val data = adapter.data[position] as IsoyuBean.DataBean.VideoListBean
                startActivity(Intent(context, IjkPlayerActivity::class.java)
                    .putExtra("title", data.title)
                    .putExtra("url", data.mp4_url)
                    .putExtra("imageUrl", data.cover))
            }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recycler.layoutManager = LinearLayoutManager(context)
        mAdapter.openLoadAnimation()
        // 当列表滑动到倒数第N个Item的时候(默认是1)回调onLoadMoreRequested方法
        mAdapter.setPreLoadNumber(5)
        mAdapter.setHasStableIds(true)

        recycler.adapter = mAdapter

    }

    fun loadData(showLoading: Boolean) {
        mBaseModel?.loadData(showLoading)
    }

    override fun onRefresh() {
        loadData(true)
    }


}
